// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html


import LanguageMng from "../../Managers/LanguageMng";
import LanguageMngTs from "../../Managers/LanguageMngTs";

cc.Class({
    extends: cc.Component,

    properties: {

        labelMyCoin:{
            default:null,
            type:cc.Label
        },

        normalBonusParent:{
            default:null,
            type:cc.Node
        },

        day7Node:{
            default:null,
            type:cc.Node
        },

        timeNode:{
            default:null,
            type:cc.Node
        },

        canCollectNode:{
            default:null,
            type:cc.Node
        },

        labelTime:{
            default:null,
            type:cc.Label
        },

        coinPrefab:{
            default:null,
            type:cc.Prefab
        },

        contentWindow:{
            default:null,
            type:cc.Node
        },

        coinIcon:{
            default:null,
            type:cc.Node,
        },

        _dayItems:[],
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

    },

    showDailyBonus:function () {
        this.contentWindow.getComponent("ScaleOut").startScaleOut(null)
    },

    _initDaysItem:function () {
        let normalDayNodes = this.normalBonusParent.children
        for(let i=0;i<normalDayNodes.length;i++){
            let itemScript = normalDayNodes[i].getComponent("DailyBonusItem")
            this._dayItems.push(itemScript)
        }
        let day7Script = this.day7Node.getComponent("DailyBonusItem")
        this._dayItems.push(day7Script)
    },

    start () {

    },

    update (dt) {
        if(!this._inited) return
        this._leftTime -= dt
        this._getLastTimeToGet(this._lastGetTime)

        if(this.startMyCoinAnim){
            this._updateCoinLabelAnim(dt)
        }
    },

    onBonusClicked (event) {
        cc.gg.logicUtil.showRegisterScene(function () {
            this._tryCollectActivity1002(event)
        }.bind(this))
    },

    async _tryCollectActivity1002(event){
        let btnNode = event.target

        let script = btnNode.getComponent("DailyBonusItem")
        if(script._isDead){
            return
        }

        if(!script.isNextCollected){
            return
        }

        if(!this.canCollectNow){
            let title = LanguageMng.getSentence(3) //Tournament
            let btnStr = LanguageMng.getSentence(181)   //ok
            let contentStr = LanguageMng.getSentence(222)   //You can get it at 24:00 today.
            let cb = function () {
                cc.gg.toastMgr.removeDialog()
            }.bind(this)
            cc.gg.toastMgr.showDialogOneButton(title,btnStr,contentStr,cb)
            return
        }

        if(this._data.status === 1 && !cc.gg.gameDataUtil.guestCanCollect){
            this._showBindNotice()
            return
        }

        if(btnNode !== this._nextRewardNode){
            cc.gg.toastMgr.showToast("Time not fit.",1)
            return
        }

        let canCollect = cc.gg.logicUtil.canActivityCollect(this._lastGetTime)
        if(canCollect){
            cc.log("可以领取！")
        }

        await cc.gg.toastMgr.showNetWaitting()
        let succ = await cc.gg.logicUtil.collectActivity(1002)
        cc.gg.toastMgr.removeNetWaitting()
        if(succ){
            this._data.record = {count:++this.deadIdx,ts:parseInt(new Date().getTime()/1000)}
            this.initDailyBonus(this._data,this._lobbyMgr)
            this.startGainCoinAnim(event.target)
            this.startCoinLabelAnim(script.coin)
            cc.gg.dataMgr.getPlayerInfo().deposit += script.coin
            cc.log("大厅金币更新为：",cc.gg.dataMgr.getPlayerInfo().deposit+cc.gg.dataMgr.getPlayerInfo().winnings)
            this.uiMgr.updateLobbyUser()
        }else {
            let content = LanguageMngTs.getSentence(326)    //Collect reward faild.
            cc.gg.toastMgr.showToast(content,1)
        }
    },


    _showBindNotice:function () {
        let title = LanguageMng.getSentence(3)  //Notice
        let positiveStr = LanguageMng.getSentence(57)   //Yes
        let passiveStr = LanguageMng.getSentence(179)   //Cancel
        let content = LanguageMng.getSentence(188)  //You must bind your mobile.
        cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,content,
            function () {
                cc.gg.toastMgr.removeDialog()
                // cc.find("Canvas/UIManager").emit("ui_show_kyc")
                cc.loader.loadRes("windows/bindMobile",cc.Prefab,function (err, prefab) {
                    let newBindWin = cc.instantiate(prefab)
                    newBindWin.getComponent("BindMobile")
                    cc.find("Canvas").addChild(newBindWin)
                }.bind(this))
            }.bind(this),
            function () {
                cc.gg.toastMgr.removeDialog()
            }
        )
    },

    startCoinLabelAnim:function (count) {
        this.addCoin = count
        this.startMyCoinAnim = true
    },

    _updateCoinLabelAnim:function (dt) {
        if(this.addCoin === 0){
            this.startMyCoinAnim = false
            return
        }

        let addCoin = this.addCoin > 5 ? 5 : this.addCoin
        this.addCoin -= addCoin
        // this.labelMyCoin.string = parseInt(this.labelMyCoin.string)+addCoin
        this._realCoin += addCoin
        this._setMyCoin(this._realCoin)
    },

    _setMyCoin:function (newValue) {
        this.labelMyCoin.string = cc.gg.gameDataUtil.getStringOfRupee(newValue)
    },

    startGainCoinAnim:function (node) {
        let tarNode = this.labelMyCoin.node
        let tarPos = tarNode.parent.convertToWorldSpaceAR(tarNode.position)
        tarPos = node.convertToNodeSpaceAR(tarPos)

        let coinCount = 8+(4*this._dayItems.indexOf(node.getComponent("DailyBonusItem")))
        cc.log("生成",coinCount)
        let coinToCenterX = 0
        let coinToCenterY = 0 - 50
        for(let i=0;i<coinCount;i++){
            let newCoin = cc.instantiate(this.coinPrefab)
            let rdmXSym = Math.random()>0.5?true:false
            let rdmYSym = Math.random()>0.5?true:false
            let rdmX = Math.random()*110 * (rdmXSym?1:-1)+coinToCenterX
            let rdmY = Math.random()*110 * (rdmYSym?1:-1)+coinToCenterY
            cc.log("x:",rdmX,"y:",rdmY)
            node.addChild(newCoin)

            // var bezier = [cc.v2(rdmX, rdmY), cc.v2(300, -windowSize.height / 2), cc.v2(300, 100)];
            // var bezierTo = cc.bezierTo(2, bezier);

            let rdmTarXSym = Math.random()>0.5?true:false
            let rdmTarYSym = Math.random()>0.5?true:false
            let rdmTarX = Math.random()*20 * (rdmTarXSym?1:-1)+tarPos.x
            let rdmTarY = Math.random()*20 * (rdmTarYSym?1:-1)+tarPos.y
            let moveToFinal = cc.moveTo(Math.random()*0.4,rdmTarX,rdmTarY).easing(cc.easeIn(3.0));
            let moveOut = cc.moveTo(Math.random()*0.1+0.1,rdmX,rdmY).easing(cc.easeOut(3.0));
            let sound = cc.callFunc(function () {
                cc.find("Canvas/SoundManager").getComponent("SoundManager").playCoinSound()
            },this)
            let des = cc.removeSelf()
            newCoin.runAction(cc.sequence(moveOut,moveToFinal,sound,des))
        }
    },

    onDailyBonusCloseButtonClicked:function (event) {
        this.node.destroy()
        // this._lobbyMgr.refreshUserInfo()
        cc.loader.releaseRes("Activity/DailyBonus")
    },

    initDailyBonus:function (data,lobbyMgr) {

        this.canCollectNow = false
        this._lobbyMgr = lobbyMgr
        this._dayItems = []
        this._data = data
        this._inited = true
        let info = cc.gg.dataMgr.getPlayerInfo()
        this._initUI(info.deposit + info.winnings)
        this._initDaysItem()
        this.initItemScript(data)
        this._initTimeStamps(data.record)

        let dayData = data.data
        let record = data.record
        this.deadIdx = record ? record.count : 0
        this._nextRewardNode = this._dayItems[this.deadIdx] ? this._dayItems[this.deadIdx].node : null
        cc.log("下个会被领取的节点为：",this._nextRewardNode?this._nextRewardNode.name:"没了")
    },

    _initTimeStamps:function (record) {
        this._lastGetTime = record ? record.ts : 0

        if(record){
            let canCollect = cc.gg.logicUtil.canActivityCollect(this._lastGetTime)
            if(canCollect){
                this._leftTime = 0
                return
            }

            cc.log("上一次领奖的时间是：",this._lastGetTime)
            this._lastGetTime = new Date().getTime()/1000
            cc.log("现在的时间是：",this._lastGetTime)
            this._leftTime = 86400 - this._lastGetTime % 86400 - 5.5 * 3600
            cc.log("剩余时间：",this._leftTime)
        }else {
            this._leftTime = 0
        }
    },

    _initUI:function (coin) {
        this.coinIcon.active = !cc.gg.gameDataUtil.showRupee
        // this.labelMyCoin.string = coin
        this._setMyCoin(coin)
        this._realCoin = coin
    },

    _getLastTimeToGet:function () {
        //今天的零点
        // let minus = parseInt((this._todayZeroStamp - lastGetTs)/1000)
        // if(!lastGetTs || minus < 0){
        //     cc.log("已经过了时间，可以领了")
        //     this.timeNode.active = false
        //     this.canCollectNode.active = true
        // }else {
        //     this.timeNode.active = true
        //     this.canCollectNode.active = false
        // }

        let minus = this._leftTime
        if(minus <= 0){
            // cc.log("已经过了时间，可以领了")
            this.canCollectNow = true
            this.timeNode.active = false
            this.canCollectNode.active = true
        }else {
            this.canCollectNow = false
            this.timeNode.active = true
            this.canCollectNode.active = false
        }

        var h=parseInt(minus/3600);
        var m1=parseInt(minus%3600/60)
        var s=parseInt(minus%60)
        h = h<10?("0"+h):h;
        m1 = m1<10?("0"+m1):m1;
        s = s<10?("0"+s):s;
        this.labelTime.string = h +":"+m1 +":"+s
    },


    initItemScript:function (data) {
        // {
        //     "succ": true,
        //     "status": 200,
        //     "code": 0,
        //     "data": [
        //     {
        //         "id": 1002,
        //         "status": 1,
        //         "done": false,
        //         "data": [
        //             {
        //                 "day": 1,
        //                 "coin": 200
        //             },
        //             {
        //                 "day": 2,
        //                 "coin": 240
        //             },
        //             {
        //                 "day": 3,
        //                 "coin": 300
        //             },
        //             {
        //                 "day": 4,
        //                 "coin": 350
        //             },
        //             {
        //                 "day": 5,
        //                 "coin": 400
        //             },
        //             {
        //                 "day": 6,
        //                 "coin": 500
        //             },
        //             {
        //                 "day": 7,
        //                 "coin": 800
        //             }
        //         ],
        //         "record": {
        //             "count": 1,  //0代表该领第一天的了
        //             "ts": 1584070963 //最后一次领取时间，超过第二天24点就可以再领一次了
        //         }
        //     }
        // ],
        //     "msg": "Success"
        // }
        let activityStatus = data.status
        let dayData = data.data
        let record = data.record
        this.deadIdx = record ? record.count : 0

        for(let i=0;i<this._dayItems.length;i++){
            let dayItem = this._dayItems[i]
            let dayDatum = dayData[i]
            let isDead = i < this.deadIdx
            let isNextCollected = i === this.deadIdx
            dayItem.initDailyBonusItem(this,dayDatum,isDead,isNextCollected)
        }
    }
});
